import { ResultMsg } from "@/common/enum/result-msg.enum";

interface PageInfo {
    pageNum: number; // 当前页码
    pageSize: number; // 每页条数
    total: number; // 总条数
    totalPage: number; // 总页数
}

interface meta {
    errorCode?: number; // 错误码
    page?: PageInfo; // 分页信息
}

/** API调用返回的结果 */
export default class Result<T> {
    /** 是否成功: true成功 false失败 */
    success: boolean;

    /** 提示信息 */
    message: string | string[];

    /** 业务数据 */
    data: T | null;

    /** 错误码 */
    errorCode?: number;

    /** 分页信息 */
    page?: PageInfo;

    constructor(success: boolean, message: string, data: T | null = null, meta?: meta) {
        this.success = success;
        this.message = message;
        this.data = data;
        if (meta?.errorCode) {
            this.errorCode = meta.errorCode;
        }
        if (meta?.page) {
            this.page = meta.page;
        }
    }

    static success<T>(data: T, message = ResultMsg.HANDLE_SUCCESS): Result<T> {
        return new Result(true, message, data);
    }

    static page<T>(data: T, page: Omit<PageInfo, "totalPage">, message = ResultMsg.HANDLE_SUCCESS): Result<T> {
        return new Result(true, message, data, {
            page: {
                ...page,
                totalPage: Math.ceil(page.total / page.pageSize),
            },
        });
    }

    static error(message: string = ResultMsg.HANDLE_ERROR, errorCode?: number): Result<null> {
        return new Result(false, message, null, { errorCode });
    }

    static exception(message: string, errorCode: number): Result<null> {
        return new Result(false, message, null, { errorCode });
    }
}
